YAHOO.namespace("springmole.QueryPanel");


YAHOO.springmole.QueryPanel = function() {
	var Dom = YAHOO.util.Dom,
	    Event = YAHOO.util.Event,
	    layout = null,
	    resize = null;
	

			
	var panel = new YAHOO.widget.Panel('demo', {
	    draggable: true,
	    close: true,
	    autofillheight: "body", // default value, specified here to highlight its use in the example            
	    underlay: 'none',
	    width: '500px',
	    height: '300px',
	    xy: [500, 100]
	});
	panel.setHeader('Test Panel');
	panel.setBody('<div id="layout"></div>');
    panel.renderEvent.subscribe(function(){
        Event.onAvailable('layout', function(){
            layout = new YAHOO.widget.Layout('layout', {
                height: (panel.body.offsetHeight - 20),
                width: 480,
                units: [{
                    id: 'topUnit',
                    position: 'top',
                    height: 25,
                    resize: true,
                    header: 'SELECT * FROM table;',
                    gutter: '0 0 6 0',
                    scroll: false
                }, {
                    position: 'bottom',
                    height: 25,
                    body: 'Bottom',
                    gutter: '6 0 0 0'
                }, {
                    position: 'center',
                    body: '<div id="dynamicdata"></div>',
                    gutter: '0 0 0 0',
                    scroll: true
                }]
            });
            
	          layout.on('render', function() {
              
                var unitTop = layout.getUnitByPosition('top');
                unitTop.on('click', function(e){
                  if(!this.get('body')) {
	                  var headerText = this.get('header');
	          
	                  this.set('header', 'Query');
	                  this.set('body', '<textarea class="sqlTextEditor" id="sqlTextEditor"></textarea>');
	                  this.set('footer', '<input type="button" id="pushbutton1" name="button1" value="Add"><input type="button" id="pushbutton2" name="button2" value="Add"><input type="button" id="pushbutton3" name="button3" value="Add"><input type="button" id="pushbutton4" name="button4" value="Add"><input type="button" id="pushbutton5" name="button5" value="Add">');
	                  this.set('height', 150);
	          
	                  Dom.get('sqlTextEditor').innerHTML = headerText;
                  }
                });
                
								
								
    // Column definitions
    var myColumnDefs = [];

    // Custom parser
    var stringToDate = function(sData) {
        var array = sData.split("-");
        return new Date(array[1] + " " + array[0] + ", " + array[2]);
    };
    
    // DataSource instance
    var myDataSource = new YAHOO.util.DataSource("assets/php/json_proxy.php?");
    myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;

    
    // DataTable configuration
    var myConfigs = {
        initialRequest: "sort=id&dir=asc&startIndex=0&results=25", // Initial request for first page of data
        dynamicData: true, // Enables dynamic server-driven data
        sortedBy : {key:"id", dir:YAHOO.widget.DataTable.CLASS_ASC}, // Sets UI initial sort arrow
        paginator: new YAHOO.widget.Paginator({ rowsPerPage:25 }) // Enables pagination 
    };
    
    // DataTable instance
    var myDataTable = new YAHOO.widget.DataTable("dynamicdata", myColumnDefs, myDataSource, myConfigs);
    // Update totalRecords on the fly with value from server
    myDataTable.handleDataReturnPayload = function(oRequest, oResponse, oPayload) {
        oPayload.totalRecords = oResponse.meta.totalRecords;
        return oPayload;
    }

    myDataTable.doBeforeLoadData = function(oRequest, oResponse, oPayload){
      alert('beforeload');
      alert(oRequest);
      alert(oResponse);
      alert(oPayload);
      
      alert('avant');
    myDataSource.responseSchema = {
        resultsList: "records",
        fields: [
            {key:"id", parser:"number"},
            {key:"name"},
            {key:"date", parser:stringToDate},
            {key:"price",parser:"number"},
            {key:"number",parser:"number"}
        ],
        metaFields: {
            totalRecords: "totalRecords" // Access to value in the server response
        }
    };
    
    // Column definitions
    myColumnDefs = [ // sortable:true enables sorting
        {key:"id", label:"ID", sortable:true},
        {key:"name", label:"Name", sortable:true},
        {key:"date", label:"Date", sortable:true, formatter:"date"},
        {key:"price", label:"Price", sortable:true},
        {key:"number", label:"Number", sortable:true}
    ];    
    
      return true;
    };

            });
            
            layout.render();
        });
    });
    panel.render(document.body);
    
    resize = new YAHOO.util.Resize('demo', {
        handles: ['br'],
        autoRatio: true,
        status: false,
        minWidth: 380,
        minHeight: 300
    });
    resize.on('resize', function(args){
        var panelHeight = args.height, padding = 20;
        //Hack to trick IE into behaving
        Dom.setStyle('layout', 'display', 'none');
        this.cfg.setProperty("height", panelHeight + 'px');
        layout.set('height', this.body.offsetHeight - padding); // TODO: add px
        layout.set('width', this.body.offsetWidth - padding);
        //Hack to trick IE into behaving
        Dom.setStyle('layout', 'display', 'block');
        layout.resize();
        
    }, panel, true);
    
    
    var executeInitialQuery = function() {
      alert('initial');
    };
    
    return {
      executeInitialQuery:  executeInitialQuery
    };
    
};